from rest_framework import serializers
from .models import Card, UserCard


class CardSerializer(serializers.ModelSerializer):
    """卡牌序列化器"""
    class Meta:
        model = Card
        fields = '__all__'


class UserCardSerializer(serializers.ModelSerializer):
    """用户卡牌序列化器"""
    card = CardSerializer(read_only=True)
    card_id = serializers.IntegerField(write_only=True)
    
    class Meta:
        model = UserCard
        fields = ('id', 'card', 'card_id', 'quantity', 'obtained_at')
        read_only_fields = ('id', 'obtained_at')


class CardPurchaseSerializer(serializers.Serializer):
    """卡牌购买序列化器"""
    card_id = serializers.IntegerField()
    quantity = serializers.IntegerField(min_value=1, default=1)
    
    def validate_card_id(self, value):
        try:
            card = Card.objects.get(id=value, is_active=True)
        except Card.DoesNotExist:
            raise serializers.ValidationError("卡牌不存在或已下架")
        return value
